package com.chuangmei.com.arindoorlocationsystem.ar;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.chuangmei.com.arindoorlocationsystem.R;
import com.chuangmei.com.arindoorlocationsystem.base.BaseActivity;
import com.chuangmei.com.arindoorlocationsystem.dialog.VideoItemDialog;
import com.chuangmei.com.arindoorlocationsystem.map.IndoorPositionActivity;
import com.chuangmei.com.arindoorlocationsystem.utils.AppActivityManagerUtils;
import com.chuangmei.com.arindoorlocationsystem.utils.Constant;
import com.chuangmei.com.arindoorlocationsystem.utils.DialogUtils;
import com.chuangmei.com.arindoorlocationsystem.utils.FileUtils;
import com.chuangmei.com.arindoorlocationsystem.utils.LogUtils;
import com.chuangmei.com.arindoorlocationsystem.video.VideoPlayActivity;

import butterknife.BindView;
import butterknife.OnClick;

public class ARStudyActivity extends BaseActivity {

    @BindView(R.id.mLL_screen_recorder)
    LinearLayout mLL_screen_recorder;
    @BindView(R.id.mBT_screen_recorder)
    Button mBT_screen_recorder;
    @BindView(R.id.mBT_open_save_video_dir)
    Button mBT_open_save_video_dir;

    private static final int RECORD_REQUEST_CODE = 101;
    private static final int STORAGE_REQUEST_CODE = 102;
    private static final int AUDIO_REQUEST_CODE = 103;

    private MediaProjection mediaProjection;//录制视频的工具
    private MediaProjectionManager projectionManager;
    private ARPermissionManage arPermissionManage;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_arstudy);
    }

    @Override
    protected void initView() {
        if (systemVersionDetermine()) {
            // 判断是否已有视频文件，没有则隐藏
            if (FileUtils.dirExists(Constant.dir_video)) {
                //判断文件夹中是否有视频，没有则隐藏打开文件夹
                if (FileUtils.dirIsNull(Constant.dir_video)) {
                    mBT_open_save_video_dir.setVisibility(View.GONE);
                } else {
                    mBT_open_save_video_dir.setVisibility(View.VISIBLE);
                }
            } else {//没有文件夹创建新的并且隐藏开启按钮
                FileUtils.CheckDir(Constant.dir_video);
                mBT_open_save_video_dir.setVisibility(View.GONE);
            }


            projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
            // 启动 RecordService
            startService(new Intent(this, RecordService.class));
            arPermissionManage = new ARPermissionManage(this);
            arPermissionManage.initPermission();
            Intent intent = new Intent(this, RecordService.class);
            bindService(intent, connection, BIND_AUTO_CREATE);
        }
    }


    /**
     * 判定系统版本需大于5.0
     *
     * @return
     */
    private boolean systemVersionDetermine() {
        boolean flag = true;
        //判定系统版本过低
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        } else {
            LogUtils.showToastShort("Android版本太低，无法使用录屏功能");
            mBT_screen_recorder.setEnabled(false);
            mBT_open_save_video_dir.setEnabled(false);
            mLL_screen_recorder.setVisibility(View.GONE);
            flag = false;
        }
        return flag;
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode != 101) {
            Log.e("HandDrawActivity", "error requestCode =" + requestCode);
        }
        if (resultCode != RESULT_OK) {
            Toast.makeText(this, "捕捉屏幕被禁止", Toast.LENGTH_SHORT).show();
            return;
        }
        mediaProjection = projectionManager.getMediaProjection(resultCode, data);
        recordService.setMediaProject(mediaProjection);
        /*获得服务状态回调*/
        recordService.recordingEndListener(new ServiceCallBack() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.showToastShort("屏幕开始录制...");
                    }
                });
            }

            @Override
            public void onStop(final String fileDir, final String videoSaveName) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //询问是否打开视频文件展示界面
                        DialogUtils.showNoTitleDialog(ARStudyActivity.this, videoSaveName + " 保存成功\n" +
                                "是否预览视频?", false, new
                                DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击确定打开预览录制视频
                                        Intent intent = new Intent(ARStudyActivity.this, VideoPlayActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("video_uri", fileDir + videoSaveName);
                                        bundle.putInt("video_screen_orientation", ActivityInfo
                                                .SCREEN_ORIENTATION_PORTRAIT);
                                        intent.putExtras(bundle);
                                        ARStudyActivity.this.startActivity(intent);
                                    }
                                }, null);
                    }
                });
            }
        });
        //开始录屏
        if (recordService.startRecord()) {
            mBT_screen_recorder.setText("停止录屏");
        } else {//开启失败
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtils.showToastShort("屏幕录制开启失败");
                }
            });
        }
    }

    /**
     * 如果不授予权限则隐藏录屏按键
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RECORD_REQUEST_CODE) {
            for (int results : grantResults) {
                if (results != PackageManager.PERMISSION_GRANTED) {
                    LogUtils.showToastShort("缺少录屏所需权限,录屏功能不可用");
                    mBT_screen_recorder.setEnabled(false);
                    mBT_screen_recorder.setVisibility(View.GONE);
                }
            }

        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @OnClick({R.id.mBT_screen_recorder, R.id.mBT_open_save_video_dir, R.id.mBT_to_map})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mBT_screen_recorder:
                if (recordService.isRunning()) {
                    recordService.stopRecord();
                    mBT_screen_recorder.setText("开始录屏");
                } else {
                    Intent captureIntent = projectionManager.createScreenCaptureIntent();
                    startActivityForResult(captureIntent, RECORD_REQUEST_CODE);//正常情况是要执行到这里的,作用是申请捕捉屏幕
                }
                break;
            case R.id.mBT_open_save_video_dir:
                VideoItemDialog videoItemDialog = new VideoItemDialog(this);


                videoItemDialog.show();

                break;
            case R.id.mBT_to_map:
                Intent intent = new Intent(this, IndoorPositionActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }


    @Override
    protected void onPause() {
        /*解绑服务*/
        if (recordService.isRunning()) {
            mBT_screen_recorder.setText("开始录屏");
            recordService.stopRecord();
            unbindService(connection);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private RecordService recordService;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
        /*绑定服务后回调*/
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            RecordService.RecordBinder binder = (RecordService.RecordBinder) service;
            recordService = binder.getRecordService();
            //设置屏幕宽高和dpi
            recordService.setScreenSize(metrics.widthPixels, metrics.heightPixels - AppActivityManagerUtils
                    .getInstance().getStatusBarHeight(ARStudyActivity.this), metrics.densityDpi)
            ;
            mBT_screen_recorder.setEnabled(true);
            mBT_screen_recorder.setText(recordService.isRunning() ? "停止录屏" : "开始录屏");
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        }
    };


}
